@extends('layouts.article')

@section('includeThirdPart')
<style>
    #form-container {
    width: 500px;
    }

    .row {
    margin-top: 15px;
    }
    .row.form-group {
    padding-left: 15px;
    padding-right: 15px;
    }
    .btn {
    margin-left: 15px;
    }

    .change-link {
    background-color: #000;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
    bottom: 0;
    color: #fff;
    opacity: 0.8;
    padding: 4px;
    position: absolute;
    text-align: center;
    width: 150px;
    }
    .change-link:hover {
    color: #fff;
    text-decoration: none;
    }

    img {
    width: 150px;
    }

    #editor-container {
    height: 130px;
    }
</style>
@endsection

@section('articleContent')
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">新增一篇文章</div>
                <div class="panel-body">
                    <form method="POST" action="{{ url('blog/article/') }}">
                        {!! csrf_field() !!}
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="form-group">
                                    <label for="display_name">Display name</label>
                                    <input class="form-control" name="title" type="text" value="Wall-E">
                                </div>
                                <div class="form-group">
                                    <label for="location">Location</label>
                                    <input class="form-control"  name="location" type="text" value="Earth">
                                </div>
                            </div>
                        </div>
                        <div class="row form-group">
                            <label for="about">About me</label>
                            <input name="body" type="hidden">
                            <div id="editor-container">
                            </div>
                        </div>
                        <div class="row">
                            <button class="btn btn-primary" type="submit">Save Profile</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('bodyScript')
<script>

var toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],
  ['link', 'image', 'video'],
  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  [{ 'align': [] }],

  ['clean']                                         // remove formatting button
];
var quill = new Quill('#editor-container', {
    modules: {
      toolbar: toolbarOptions
    },
    placeholder: 'Compose an epic...',
    theme: 'snow'
  });

var form = document.querySelector('form');
form.onsubmit = function() {
  // Populate hidden form on submit
  var body = document.querySelector('input[name=body]');
  body.value = JSON.stringify(quill.getContents());
  form.submit();
};

var IMGUR_API_URL = '{{ url("file/uploadfile") }}';
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
{{-- var IMGUR_CLIENT_ID = 'bcab3ce060640ba';

function imageHandler(image, callback) {
  var data = new FormData();
  data.append('image', image);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', IMGUR_API_URL, true);
  xhr.setRequestHeader('Authorization', 'Client-ID ' + IMGUR_CLIENT_ID);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      var response = JSON.parse(xhr.responseText);
      if (response.status === 200 && response.success) {
        callback(response.data.link);
      } else {
        var reader = new FileReader();
        reader.onload = function(e) {
          callback(e.target.result);
        };
        reader.readAsDataURL(image);
      }
    }
  }
  xhr.send(data);
} --}}

function selectLocalImage() {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.click();

    // Listen upload local image and save to server
    input.onchange = () => {
      const file = input.files[0];

      // file type is only image.
      if (/^image\//.test(file.type)) {
        saveToServer(file);
      } else {
        alert('You could only upload images.');
      }
    };
  }


  function OnProgress(event, position, total, percentComplete){
    //Progress bar
    console.log(total);
    $('#pb').width(percentComplete + '%') //update progressbar percent complete
    $('#pt').html(percentComplete + '%'); //update status text
}
  /**
   * Step2. save to server
   *
   * @param {File} file
   */
  function saveToServer(file) {
    const fd = new FormData();
    fd.append('image', file);

    {{-- const xhr = new XMLHttpRequest();
    xhr.open('POST', IMGUR_API_URL);
    xhr.onload = () => {
      if (xhr.status === 200) {
        // this is callback data: url
        const url = JSON.parse(xhr.responseText).data;
        insertToEditor(url);
      }
    };
    xhr.send(fd); --}}

    $.ajax({
      type: "POST",
      url: IMGUR_API_URL,
      // data: {_token: CSRF_TOKEN, file:fd},
      data: fd,
      headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
      processData: false,
      contentType: false,
      success: function (data) {
        const url = data['url'];
        insertToEditor(url);
      },
      //beforeSubmit: beforeSubmit,
      uploadProgress:OnProgress, 
  });
  }

  /**
   * Step3. insert image url to rich editor.
   *
   * @param {string} url
   */
  function insertToEditor(url) {
    // push image url to rich editor.
    const range = quill.getSelection();
    quill.insertEmbed(range.index, 'image', url);
  }

  
  quill.getModule('toolbar').addHandler('image', () => {
    selectLocalImage();
  });
</script>
@endsection